package org.rcy.ruicingmarket.comment;

import org.rcy.ruicingmarket.common.result.PageResult;
import org.rcy.ruicingmarket.common.utils.IdWorker;
import com.rcy.feignclients.user.UserFeignClient;
import com.rcy.vo.comment.CommentAddVo;
import com.rcy.vo.comment.CommentEditVo;
import com.rcy.vo.comment.CommentShowVo;
import com.rcy.vo.user.UserShowVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author RuicyWu
 * @Date 2022/3/25 10:12
 */
@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
//    @Autowired
//    private UserClient userClient;


    /**
     * 添加评论
     * @param vo
     */
    public void add(CommentAddVo vo)
    {
        Comment comment = new Comment();
        BeanUtils.copyProperties(vo,comment);
        comment.setUpdatetime(new Date());
        comment.setIndex(idWorker.nextId()+"");
        comment.setThumbup(0);
        commentRepository.save(comment);
    }

    /**
     * 修改评论
     * @param vo
     */
    public void update(CommentEditVo vo)
    {
        Update update = new Update();
        Assert.notNull(vo.getId(), "id为空");
        Assert.notNull(vo.getUid(), "uid为空");
        Assert.notNull(vo.getSkuId(), "skuId为空");
        update.set("id",vo.getId());
        update.set("uid",vo.getUid());
        update.set("skuId",vo.getSkuId());
        if(StringUtils.isNotEmpty(vo.getContent())){
            update.set("content",vo.getContent());
        }
        Criteria criteria = Criteria.where("id")
                .is(vo.getId());
        Query query = new Query(criteria);
        mongoTemplate.updateFirst(query, update, Comment.class);

    }

    /**
     * 通过id删除评论
     * @param id
     */
    public void removeById(String id)
    {
        commentRepository.deleteCommentByParentid(id);
        commentRepository.deleteById(id);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public Comment findById(String id)
    {
        return commentRepository.findById(id).get();
    }

    /**
     * 根据上级id查询
     * @param
     * @return
     */
    public PageResult<CommentShowVo> findByParentId(CommentQueryRequest request)
    {
        Page<Comment> byParentid = commentRepository.findByParentid(request.getParentid(), PageRequest.of(request.getPageNo() - 1, request.getPageSize()));
        List<Comment> content = byParentid.getContent();
        List<CommentShowVo> vos = new ArrayList<>();
        for (Comment comment : content) {
            CommentShowVo commentShowVo = new CommentShowVo();
            BeanUtils.copyProperties(comment,commentShowVo);
            ResultMessage<UserShowVo> byId = userFeignClient.getById(Long.parseLong(comment.getUid()));
            if(byId.isFlag()&&byId.getData() != null){
                commentShowVo.setUser(byId.getData());
            }
            Long aLong = commentRepository.countByParentid(comment.getId());
            if(aLong > 0){
                commentShowVo.setReply(true);
            }
            vos.add(commentShowVo);
        }
        return new PageResult<CommentShowVo>(request.getPageNo(),request.getPageSize(),byParentid.getTotalElements(),vos);
    }

    /**
     * 点赞
     * @param id
     */
    public void commentThumbup(String id,String uid)
    {
           String isThumbup = (String)redisTemplate.opsForValue().get("thumbup"+id+"_"+uid);
        if(isThumbup != null){
            throw new RuntimeException("您已点过赞");
        }else {
            redisTemplate.opsForValue().set("thumbup"+id+"_"+uid,"1");
        }
        //不允许重复点赞,用户点赞后需要记录到redis中，下次点赞前先到redis中查询
        Query query=new Query(Criteria.where("_id").is(id));
        Update update=new Update();
        update.inc("thumbup");
        mongoTemplate.updateFirst(query,update,"bsComment");
    }

    /**
     * 取消点赞
     * @param id
     * @param uid
     */
    public void cancelCommentThumbup(String id,String uid)
    {
           redisTemplate.delete("thumbup"+id+"_"+uid);
        //不允许重复点赞,用户点赞后需要记录到redis中，下次点赞前先到redis中查询
        Query query=new Query(Criteria.where("_id").is(id));
        Update update=new Update();
        update.inc("thumbup",-1);
        mongoTemplate.updateFirst(query,update,"bsComment");
    }

    /**
     * 查询顶级评论
     * @param
     * @return
     */
    public List<CommentShowVo> getCommentList(CommentQueryRequest request){
        List<CommentShowVo> vos = new ArrayList<>();
        Page<Comment> comments = commentRepository.findCommentsBySkuIdAndParentId(request.getSkuId(), null, PageRequest.of(request.getPageNo() - 1, request.getPageSize()));
        for (Comment comment : comments.getContent()) {
            CommentShowVo commentShowVo = new CommentShowVo();
            BeanUtils.copyProperties(comment,commentShowVo);
            ResultMessage<UserShowVo> byId = userFeignClient.getById(Long.parseLong(comment.getUid()));
            if(byId.isFlag()&&byId.getData() != null){
                commentShowVo.setUser(byId.getData());
            }
            Long aLong = commentRepository.countByParentid(comment.getId());
            if(aLong > 0){
                commentShowVo.setReply(true);
            }
            vos.add(commentShowVo);
        }
        return vos;
    }
}
